package com.star.gc4.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.star.gc4.common.R;
import com.star.gc4.entity.Menu;
import com.star.gc4.entity.Message;
import com.star.gc4.entity.Msongs;
import com.star.gc4.service.MenuService;
import com.star.gc4.service.MsongsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@RestController
@RequestMapping("/msongs")
public class msongsController {
    @Autowired
    private MsongsService msongsService;

    @Autowired
    private MenuService menuService;
    /*
     * 添加歌曲进歌单
     * */
    @PostMapping("/save")
    public R<String> saveIntoMenu(@RequestBody Msongs msongs){


        LambdaQueryWrapper<Msongs> querywrapper1 = new LambdaQueryWrapper<>();
        querywrapper1.eq(Msongs::getSongid,msongs.getSongid()).eq(Msongs::getMenuid,msongs.getMenuid());
        int count1 = msongsService.count(querywrapper1);
        if(count1 == 0){
            msongsService.save(msongs);
        }else {
            return R.error("歌单已存在该歌曲");
        }


        LambdaQueryWrapper<Msongs> querywrapper = new LambdaQueryWrapper<>();
        querywrapper.eq(Msongs::getMenuid,msongs.getMenuid());
        int count = msongsService.count(querywrapper);

        UpdateWrapper<Menu> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("count", count);
        updateWrapper.eq("id", msongs.getMenuid());
        menuService.update(updateWrapper);

        return R.success("添加成功");
    }

    /*
    * 删除歌单中的歌曲
    * 歌单Id ，歌曲Id
    * */
    @GetMapping("/delete")
    public R<String> delete(Integer menuid ,String[] ids){
        msongsService.removeByIds(Arrays.asList(ids));

        LambdaQueryWrapper<Msongs> querywrapper = new LambdaQueryWrapper<>();
        querywrapper.eq(Msongs::getMenuid,menuid);
        int count = msongsService.count(querywrapper);

        UpdateWrapper<Menu> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("count", count);
        updateWrapper.eq("id", menuid);
        menuService.update(updateWrapper);

        return R.success("删除成功");
    }

    /*
     * 根据歌单id，menuid分页查询结果
     * */
    @GetMapping("/page")
    public R<Page> page(Integer page,Integer pageSize,Integer menuid ){
        Page pageinfo =new Page(page,pageSize);
        LambdaQueryWrapper<Msongs> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(Msongs::getMenuid,menuid);

        msongsService.page(pageinfo,queryWrapper);
        return R.success(pageinfo);
    }


}
